package com.useeinfo.oa.modules.security.entity;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.entity.SuperClassEntity;
import com.useeinfo.framework.sugar.tools.CommonSugar;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.repair.entity.RepairPartner;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * 系统账号表
 */
@Entity
@Table(name = "system_user")
public
class SystemUser extends SuperClassEntity<SystemUser> {

    /**
     * 用户登陆帐号
     */
    private String userAccount;

    /**
     * 用户手机号
     */
    private String mobile;

    /**
     * 用户邮箱
     */
    private String email;

    /**
     * 用户登陆密码
     */
    private String userPassword;

    /**
     * 用户姓名
     */
    private String userName;
    /**
     * 工号
     */
    private String workNo;
    /**
     * 性别
     */
    private String sex;

    /**
     * 用戶唯一编码---32位随机字符串 UUID.randomUUID()
     */
     private String uniqueid;
    /**
     * 所属岗位
     */
    @ManyToMany()
    @JoinTable(name = "system_user_2_position", joinColumns = @JoinColumn(name = "system_user_id"), inverseJoinColumns = @JoinColumn(name = "position_id"))
    private Set<Position> positionSet = new HashSet<>();

    /**
     * 所属区域
     */
    @ManyToMany()
    @JoinTable(name = "system_user_2_area", joinColumns = @JoinColumn(name = "system_user_id"), inverseJoinColumns = @JoinColumn(name = "area_id"))
    private Set<Area> areaSet = new HashSet<>();

    /**
     * 企业系统用户和普通用户的映射关系
     */
    @OneToMany(mappedBy = "systemUser")
    private Set<EnterprisePersonnelSystemUser>enterprisePersonnelSystemUserSet = new HashSet<>();

    @OneToMany(mappedBy = "partner")
    private Set<RepairPartner> repairPartnerSet = new HashSet<>();

    /**
     * 多对多企业
     */
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "system_user_2_enterprise", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "enterprise_id"))
    private Set<Enterprise> enterpriseSet = new HashSet<>();

    @OneToMany(mappedBy = "systemUser")
    private Set<SystemUserOrganization>systemUserOrganizationSet = new HashSet<>();

    /**
     * 是否被禁用 true-正常 false-已禁用
     */
    private boolean enabled;
    /**
     * 所属操作角色  具体数据为枚举：OperationRoleEnum
     */
    private String operationRole; // admin:超级管理员 enterprise:企业管理者  common:普通人员

    public SystemUser() {
    }

    public SystemUser(String userAccount, String userPassword, String userName) {
        this.userAccount = userAccount;
        this.userPassword = userPassword;
        this.userName = userName;
    }

    @Override
    public JSONObject toJSONObject() {
        JSONObject jsonObject = super.toJSONObject();

        jsonObject.put("userId", CommonSugar.getTypedDefault(getId(), 0L));
        jsonObject.put("createTime", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(getCreateDate()), ""));
        jsonObject.put("userAccount", CommonSugar.getTypedDefault(getUserAccount(), ""));
        //jsonObject.put("userPassword", CommonSugar.getTypedDefault(getUserPassword(), ""));
        jsonObject.put("userName", CommonSugar.getTypedDefault(getUserName(), ""));
        jsonObject.put("mobile", CommonSugar.getTypedDefault(getMobile(), ""));
        jsonObject.put("email", CommonSugar.getTypedDefault(getEmail(), ""));
        jsonObject.put("workNo", CommonSugar.getTypedDefault(getWorkNo(), ""));
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);

        Set<Position>positions = getPositionSet();
        Position position = getPosition(enterprise, getPositionSet());
        if (null != position) {
            jsonObject.put("position", StringConverters.null2String(position.getName()));
            jsonObject.put("positionId", position.getId());
        } else {
            jsonObject.put("position", "");
            jsonObject.put("positionId", "");
        }
        SystemUserOrganization systemUserOrganization = getOrganization(enterprise, getSystemUserOrganizationSet());
        if (null != systemUserOrganization) {
            if(null!=systemUserOrganization.getOrganization()) {
                jsonObject.put("organization", StringConverters.null2String(systemUserOrganization.getOrganization().getOrganizationName()));
                jsonObject.put("organizationId", systemUserOrganization.getOrganization().getId());
            }else {
                jsonObject.put("organization", "");
                jsonObject.put("organizationId", "");
            }
            jsonObject.put("leader",systemUserOrganization.isLeader());
        } else {
            jsonObject.put("organization", "");
            jsonObject.put("organizationId", "");
            jsonObject.put("leader",false);
        }

        jsonObject.put("roleName","");
        jsonObject.put("roleId","");

        return jsonObject;
    }


    public JSONObject toJSONObjectDetail() {
        JSONObject jsonObject = super.toJSONObject();

        jsonObject.put("userId", CommonSugar.getTypedDefault(getId(), 0L));
        jsonObject.put("createTime", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(getCreateDate()), ""));
        jsonObject.put("userAccount", CommonSugar.getTypedDefault(getUserAccount(), ""));
        jsonObject.put("userPassword", CommonSugar.getTypedDefault(getUserPassword(), ""));
        jsonObject.put("userName", CommonSugar.getTypedDefault(getUserName(), ""));
        jsonObject.put("mobile", CommonSugar.getTypedDefault(getMobile(), ""));
        jsonObject.put("email", CommonSugar.getTypedDefault(getEmail(), ""));
        jsonObject.put("workNo", CommonSugar.getTypedDefault(getWorkNo(), ""));
        jsonObject.put("password", CommonSugar.getTypedDefault(getUserPassword(), ""));
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);

        Set<Position>positions = getPositionSet();
        Position position = getPosition(enterprise, getPositionSet());
        if (null != position) {
            jsonObject.put("position", StringConverters.null2String(position.getName()));
            jsonObject.put("positionId", position.getId());
        } else {
            jsonObject.put("position", "");
            jsonObject.put("positionId", "");
        }
        SystemUserOrganization systemUserOrganization = getOrganization(enterprise, getSystemUserOrganizationSet());
        if (null != systemUserOrganization) {
            if(null!=systemUserOrganization.getOrganization()) {
                jsonObject.put("organization", StringConverters.null2String(systemUserOrganization.getOrganization().getOrganizationName()));
                jsonObject.put("organizationId", systemUserOrganization.getOrganization().getId());
            }else {
                jsonObject.put("organization", "");
                jsonObject.put("organizationId", "");
            }
            jsonObject.put("leader",systemUserOrganization.isLeader());
        } else {
            jsonObject.put("organization", "");
            jsonObject.put("organizationId", "");
            jsonObject.put("leader",false);
        }

        jsonObject.put("roleName","");
        jsonObject.put("roleId","");

        return jsonObject;
    }

    public Position getPosition(Enterprise enterprise, Set<Position> positionSet) {
        for (Position position : positionSet) {
            if (position.getEnterprise().getId().equals(enterprise.getId())) {
                return position;
            }
        }
        return null;
    }
    public SystemUserOrganization getOrganization(Enterprise enterprise,Set<SystemUserOrganization>systemUserOrganizationSet){
        for (SystemUserOrganization systemUserOrganization : systemUserOrganizationSet) {
            if (null!=systemUserOrganization.getOrganization()&&systemUserOrganization.getOrganization().getEnterprise().getId().equals(enterprise.getId())) {
                return systemUserOrganization;
            }
        }
        return null;
    }




    public JSONObject toLoginJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", CommonSugar.getTypedDefault(getId(), 0L));
        jsonObject.put("userAccount", CommonSugar.getTypedDefault(getUserAccount(), ""));
        jsonObject.put("userName", CommonSugar.getTypedDefault(getUserName(), ""));
        return jsonObject;
    }


    public JSONObject toLoginJedisJSONObject() {
        JSONObject jsonObject = super.toJSONObject();
        jsonObject.put("userAccount", CommonSugar.getTypedDefault(getUserAccount(), ""));
        jsonObject.put("userName", CommonSugar.getTypedDefault(getUserName(), ""));
        return jsonObject;
    }

    public String getUserAccount() {
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public Set<Enterprise> getEnterpriseSet() {
        return enterpriseSet;
    }

    public void setEnterpriseSet(Set<Enterprise> enterpriseSet) {
        this.enterpriseSet = enterpriseSet;
    }

    public String getOperationRole() {
        return operationRole;
    }

    public void setOperationRole(String operationRole) {
        this.operationRole = operationRole;
    }

    public String getWorkNo() {
        return workNo;
    }

    public void setWorkNo(String workNo) {
        this.workNo = workNo;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Set<Position> getPositionSet() {
        return positionSet;
    }

    public void setPositionSet(Set<Position> positionSet) {
        this.positionSet = positionSet;
    }

    public Set<Area> getAreaSet() {
        return areaSet;
    }

    public void setAreaSet(Set<Area> areaSet) {
        this.areaSet = areaSet;
    }

    public void addEnterprise(Enterprise enterprise) {
        this.enterpriseSet.add(enterprise);
    }

    public void removeEnterprise(Enterprise enterprise) {
        this.enterpriseSet.remove(enterprise);
    }

    public Set<EnterprisePersonnelSystemUser> getEnterprisePersonnelSystemUserSet() {
        return enterprisePersonnelSystemUserSet;
    }

    public void setEnterprisePersonnelSystemUserSet(Set<EnterprisePersonnelSystemUser> enterprisePersonnelSystemUserSet) {
        this.enterprisePersonnelSystemUserSet = enterprisePersonnelSystemUserSet;
    }

    public Set<SystemUserOrganization> getSystemUserOrganizationSet() {
        return systemUserOrganizationSet;
    }

    public void setSystemUserOrganizationSet(Set<SystemUserOrganization> systemUserOrganizationSet) {
        this.systemUserOrganizationSet = systemUserOrganizationSet;
    }

    public String getUniqueid() {
        return uniqueid;
    }

    public void setUniqueid(String uniqueid) {
        this.uniqueid = uniqueid;
    }

    public Set<RepairPartner> getRepairPartnerSet() {
        return repairPartnerSet;
    }

    public void setRepairPartnerSet(Set<RepairPartner> repairPartnerSet) {
        this.repairPartnerSet = repairPartnerSet;
    }

    @Override
    public boolean equals(Object obj) {

        System.out.println("------equals----");

        if (obj instanceof SystemUser) {

            SystemUser user = (SystemUser) obj;

            if (this.getId().equals(user.getId())) {
                return true;
            }

        }
        return false;

    }
}
